package settings

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
)

var Conf = new(Appcinfig)

type Appcinfig struct {
	Name      string `mapstructure:"name"`
	Mode      string `mapstructure:"mode"`
	Version   string `mapstructure:"version"`
	StartTime string `mapstructure:"start_time"`
	MachineID int64  `mapstructure:"machine_id"`
	Port      int    `mapstructure:"port"`

	*LogConfig   `mapstructure:"log"`
	*MySQLConfig `mapstructure:"mysql"`
	*RedisConfig `mapstructure:"redis"`
}

type MySQLConfig struct {
	Host        string `mapstructure:"host"`
	User        string `mapstructure:"user"`
	Password    string `mapstructure:"password"`
	DB          int    `mapstructure:"db"`
	Port        int    `mapstructure:"port"`
	MaxOpenConn int    `mapstructure:"max_open_conn"`
	MaxIdleConn int    `mapstructure:"max_idle_conn"`
}

type RedisConfig struct {
	Host     string `mapstructure:"host"`
	Password string `mapstructure:"password"`
	DB       int    `mapstructure:"db"`
	Port     int    `mapstructure:"port"`
	PoolSize int    `mapstructure:"pool_size"`
}

type LogConfig struct {
}

func Init() (err error) {
	viper.SetConfigName("config") // 指定配置文件
	viper.SetConfigType("yaml")
	viper.AddConfigPath("./conf")               // 指定查找配置文件的路径
	if err = viper.ReadInConfig(); err != nil { // 读取配置信息失败
		fmt.Println("read file err", err)
		return
	}
	//把读取到的配置信息学反序列化到Conf变量中
	//if err := viper.Unmarshal(Conf); err != nil {
	//	fmt.Println("read file err", err)
	//	return
	//}
	// 监控配置文件变化
	viper.WatchConfig()
	viper.OnConfigChange(func(in fsnotify.Event) {
		fmt.Println("配置文件修改了")
		//if err := viper.Unmarshal(Conf); err != nil {
		//	fmt.Sprintf("Unmarshal failed,err:%#v", err)
		//}
	})
	return
}
